package com.tedu.firstspringboot.controller;


import com.tedu.firstspringboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class LoginController {
    @RequestMapping("/loginUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        String loginname = request.getParameter("loginname");
        String loginpwd = request.getParameter("loginpassword");
        if ((loginname == null || loginname.trim().isEmpty()
                || loginpwd == null || loginpwd.trim().isEmpty())) {
            try {
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        System.out.println(loginname + "," + loginpwd);
        // System.out.println(123);
        File file = new File("./users/" + loginname + ".obj");
        boolean b = file.exists();
        if (!b) {
            try {
                response.sendRedirect("/login_01.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            User user = (User) ois.readObject();
            System.out.println(user);
            //int pwd=Integer.parseInt(loginpwd);
            if (user.getPassword().equals(loginpwd)) {
                response.sendRedirect("/login_success.html");
            } else {
                response.sendRedirect("/login_fail.html");
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}

